//
//  IntegralStoreViewController.m
//  IntegralDog
//
//  Created by Hanen 3G 01 on 16/1/25.
//  Copyright © 2016年 hanen. All rights reserved.
//

#import "IntegralStoreViewController.h"
#import "SDCycleScrollView.h"
#import "ImageTextButton.h"
#import "IntegralMainViewCell.h"
#import "IntegralCollectionViewCell.h"
#import "HeaderView.h"
#import "IntegralModel.h"
#import "ExRecordViewController.h"
#import "Macro.h"

#define KScreenW [UIScreen mainScreen].bounds.size.width
#define KScreenH [UIScreen mainScreen].bounds.size.height

@interface IntegralStoreViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,HeaderViewDelegate,UIAlertViewDelegate>
{
    UITableView   *_mainTableView;
    UIView        *_headView;
    
    UICollectionView *_mainColletionView;
    
    int  id1;
}

//数据源数组、、、、、
@property (nonatomic, strong) NSMutableArray  *headImageArr;//头部广告
@property (nonatomic, strong) NSMutableArray  *headBtnTitleArr;//积分 兑换原则 兑换记录
@property (nonatomic, strong) NSArray *imageArr;
@property (nonatomic, strong) NSArray *titleArr;
@property (nonatomic, strong) NSArray *subtitleArr;

@property (nonatomic, strong) NSMutableArray  *dataArray;
@end

@implementation IntegralStoreViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBarHidden = NO;
    self.navigationItem.title = @"积分商城";
    
    _dataArray = [[NSMutableArray alloc]initWithCapacity:0];
    
    [self initData];
    
//    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 15, 15 * 50 / 28)];
//    [btn addTarget:self action:@selector(backToView:) forControlEvents:UIControlEventTouchUpInside];
//    [btn setImage:[UIImage imageNamed:@"Btn_Nourmal_Jiantou"] forState:UIControlStateNormal];
//    [btn setImage:[UIImage imageNamed:@"Btn_Push_Jiantou"] forState:UIControlStateSelected];
//    UIBarButtonItem *barItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
//    self.navigationItem.leftBarButtonItem = barItem;
    
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.IntegralNum = [NSString stringWithFormat:@"%d",1000];
//    [self creatSubView];
    [self addCollectionView];
    
    
}
- (void)initData{
    NSNumber *pageNum = [NSNumber numberWithInt:1];
    NSNumber *rowsNum = [NSNumber numberWithInt:20];
    
    id str = [DataTool changeType:TOKEN];
    int uid;
    if (UID) {
        uid = UID;
    }
    
    NSDictionary *dic =@{@"token":str,@"uid":@(uid),@"page":pageNum,@"rows":rowsNum};
    [DataTool postWithUrl:INTEGRATION_STORE_URL parameters:dic success:^(id data) {
        NSDictionary *jsonDic = IntegrationJsonParserWithData(data);
        //NSLog(@"%@+++++jsondic",jsonDic);
        NSMutableArray *array = jsonDic[@"list"];
        for (int i=0; i<array.count; i++) {
            IntegralModel *model = [[IntegralModel alloc]init];
            [model setValuesForKeysWithDictionary:array[i]];
            [_dataArray addObject:model];
        }
        [_mainColletionView reloadData];
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
}
- (void)exchangeGoods:(int)gid{
    
    //__weak typeof(self) weakSelf = self;
    NSLog(@"11111++++++");
    NSNumber *gidNum = [NSNumber numberWithInt:gid];
    NSDictionary *dic =@{@"token":TOKEN,@"uid":@(UID),@"gid":gidNum};
    [DataTool postWithUrl:EXCHANGE_GOODS_URL parameters:dic success:^(id data) {
        NSDictionary *jsonDic = IntegrationJsonParserWithData(data);
        NSLog(@"%@ +-+-+-+-0000",jsonDic);
        NSString *codeStr = [NSString stringWithFormat:@"券码:%@",jsonDic[@"exchangecode"]];
        NSString *urlStr = [NSString stringWithFormat:@"复制当前兑换码,\n点击此链接%@,\n可获取兑换物品",jsonDic[@"exchangeurl"]];
        
        int code = [jsonDic[@"code"] intValue];
        if (code != 100) {
            [self.view makeToast:jsonDic[@"message"]];
        }else{
//            NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"复制当前兑换码,点击此链接%@,可获取兑换物品",urlStr]];
//            
//            [attrStr setAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:15.0f],NSForegroundColorAttributeName : fontDarkGrayColor} range:NSMakeRange(0, attrStr.length)];
//            [attrStr setAttributes:@{NSForegroundColorAttributeName : fontLightGrayColor} range:NSMakeRange(0, urlStr.length)];
        
            UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"" message:@"是否兑换此物品？" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:nil];
            UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
//                if ([[[UIDevice currentDevice] systemVersion] floatValue] == 7) {
//                    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:codeStr message:urlStr delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"打开", nil];
//                    [alertView show];
//                }
                UIAlertController *alertControl1 = [UIAlertController alertControllerWithTitle:codeStr message:urlStr preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"打开" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    //打开链接
                    
                }];
                [alertControl1 addAction:action1];
                [alertControl1 addAction:action2];
                [self presentViewController:alertControl1 animated:YES completion:nil];
            }];
            [alertControl addAction:action1];
            [alertControl addAction:action2];
            [self presentViewController:alertControl animated:YES completion:nil];
            //[self.view makeToast:jsonDic[@"message"]];
        }
    } fail:^(NSError *error) {
        
    }];

}

- (void)addCollectionView
{
    UICollectionViewFlowLayout *folwLayOut = [[UICollectionViewFlowLayout alloc] init];
    folwLayOut.minimumInteritemSpacing = 0.5;//每项
    folwLayOut.minimumLineSpacing = 1;//每行
    
    _mainColletionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, KScreenW, KScreenH - 64 - 49 - 11) collectionViewLayout:folwLayOut];
    _mainColletionView.delegate = self;
    _mainColletionView.dataSource = self;
    _mainColletionView.backgroundColor = cellGrayColor;
    [_mainColletionView registerClass:[IntegralCollectionViewCell class] forCellWithReuseIdentifier:[IntegralCollectionViewCell reuseIdentifier]];
    
    [_mainColletionView registerClass:[HeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:[HeaderView resueIdentifer]];
    [self.view addSubview:_mainColletionView];
}
#pragma mark --创建tableview
//- (void)creatSubView
//{
//    _mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, KScreenW, KScreenH) style:UITableViewStylePlain];
//    _mainTableView.delegate = self;
//    _mainTableView.dataSource = self;
//    [self.view addSubview:_mainTableView];
//    
//    _mainTableView.tableHeaderView = [self getheadView];
//}

- (UIView *)getheadView
{
    UIView *view;
    view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenW, 200)];
    //    _headView.backgroundColor = [UIColor lightGrayColor];
    CGFloat btnW = KScreenW / 3.0f;
    CGFloat btnH = 50;
    SDCycleScrollView *headScrollView = [[SDCycleScrollView alloc] initWithFrame:CGRectMake(0, 0, KScreenW, 200 - btnH)];
    headScrollView.localizationImagesGroup  = self.headImageArr;
    headScrollView.pageControlDotSize = CGSizeMake(5, 5);
    [view addSubview:headScrollView];
    
    for (int i = 0; i < self.headBtnTitleArr.count; i ++) {
        NSLog(@"%@",self.headBtnTitleArr[i]);
        ImageTextButton *btn = [[ImageTextButton alloc] initWithFrame:CGRectMake(btnW * i, _headView.frame.size.height - btnH, btnW, btnH)];
        [btn addTarget:self action:@selector(handleBtn:) forControlEvents:UIControlEventTouchUpInside];
        //        btn.backgroundColor = [UIColor redColor];
        if (i == 0) {
            NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@",self.IntegralNum,self.headBtnTitleArr[i]]];
            
            [attrStr setAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:15.0f],NSForegroundColorAttributeName : fontDarkGrayColor} range:NSMakeRange(0, attrStr.length)];
            [attrStr setAttributes:@{NSForegroundColorAttributeName : mainOrangeColor} range:NSMakeRange(0, self.IntegralNum.length)];
            
            [btn setAttributedTitle:attrStr forState:UIControlStateNormal];
            
        }else{
            
            [btn setTitle:self.headBtnTitleArr[i] forState:UIControlStateNormal];
            [btn setTitleColor:fontDarkGrayColor forState:UIControlStateNormal];
            
            btn.titleLabel.font = [UIFont systemFontOfSize:15.0f];
        }
        btn.titleLabel.textAlignment = NSTextAlignmentCenter;
        [view addSubview:btn];
    }
    return view;
}
- (void)handleBtn:(UIButton *)btn
{
    NSLog(@"%@",btn.currentAttributedTitle);
}

//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
//    
//    
//    return _headView;
//    
//}
//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
//{
//    return 15;
//}
//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
//{
//    return 10;
//}
//- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    IntegralMainViewCell *cell = [IntegralMainViewCell cellWithTableView:tableView];
//    
//    return cell;
//}

#pragma mark --collectionview
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _dataArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    IntegralCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:[IntegralCollectionViewCell reuseIdentifier] forIndexPath:indexPath];
    
    IntegralModel *model = _dataArray[indexPath.item];
    cell.titleLabel.text = model.title;
    cell.subTitleLable.text = model.intro;
    NSString *imgStr = [NSString stringWithFormat:@"%@%@",IMAGEURL,model.litimg];
    [cell.imageVie sd_setImageWithURL:[NSURL URLWithString:imgStr]];
    cell.integralNumber.text = [NSString stringWithFormat:@"%d",model.needIntegral];
    cell.model = model;
    
    [cell.exchangeBtn addTarget:self action:@selector(clickToExchangeGoods:) forControlEvents:UIControlEventTouchUpInside];
    cell.exchangeBtn.tag = indexPath.item;
    
    id1 = model.integralId;
    
    return cell;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    //从复用池中取出头部或者尾部视图 kind就会区别是头部还是尾部视图
    HeaderView *myView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:[HeaderView resueIdentifer] forIndexPath:indexPath];
    myView.delegate = self;
    
    //如果myview为空 collectionView会根据注册的类自动创建myView
    return myView;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    //如果垂直滑动 则视图宽度与屏幕一样
    //如果是水平  则视图的高度与屏幕一样// 原设总宽度290 多1 以背景色充当线条分割
    return CGSizeMake(KScreenW, 291);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return  CGSizeMake(KScreenW / 2.0-0.5 ,140);
}

- (void)jumpToOther
{
    ExRecordViewController *exchange = [[ExRecordViewController alloc] init];
    [self.navigationController pushViewController:exchange animated:YES];
}
- (void)clickToExchangeGoods:(UIButton *)sender{
    //__weak typeof(self) weakSelf = self;
    
    IntegralModel *model = _dataArray[sender.tag];
    int idd = model.integralId;
    NSLog(@"%d +++++ iddidd %@  ------%d uiduid",idd,TOKEN,UID);
    [self exchangeGoods:idd];
    
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0 ) {
        
    }if (buttonIndex == 1) {
        NSLog(@"%d++++++++alertView+++11111",id1);
        
        
    }
}

- (void)viewWillAppear:(BOOL)animated{
//    self.navigationController.navigationBarHidden = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)backToView:(UIButton *)btn
{
//    for (UIViewController *controller in self.navigationController.viewControllers) {
//        if ([controller isKindOfClass:[你要跳转到的Controller class]]) {
//            [self.navigationController popToViewController:controller animated:YES];
//        }
//    }
    [self.navigationController popViewControllerAnimated:YES];
}


@end
